class Solution {
public:
    bool check(int i, int j, vector<vector<int>>& img)
    {
        return !(i < 0 || j < 0 || i >= img.size() || j >= img[0].size());
    }

    vector<vector<int>> imageSmoother(vector<vector<int>>& img) {
        int m = img.size(), n = img[0].size();
        vector<vector<int>> ret(img);
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                int sum = img[i][j], count = 1;
                if (check(i - 1, j - 1, img))
                {
                    sum += img[i - 1][j - 1];
                    count++;
                }
                if (check(i - 1, j, img))
                {
                    sum += img[i - 1][j];
                    count++;
                }
                if (check(i - 1, j + 1, img))
                {
                    sum += img[i - 1][j + 1];
                    count++;
                }
                if (check(i, j - 1, img))
                {
                    sum += img[i][j - 1];
                    count++;
                }
                if (check(i, j + 1, img))
                {
                    sum += img[i][j + 1];
                    count++;
                }
                if (check(i + 1, j - 1, img))
                {
                    sum += img[i + 1][j - 1];
                    count++;
                }
                if (check(i + 1, j, img))
                {
                    sum += img[i + 1][j];
                    count++;
                }
                if (check(i + 1, j + 1, img))
                {
                    sum += img[i + 1][j + 1];
                    count++;
                }
                ret[i][j] = sum / count;
            }
        }
        return ret;
    }
};